package org.example.airesumescoring.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.airesumescoring.model.Users;
import org.example.airesumescoring.repository.UserRepository;
import org.example.airesumescoring.service.AuthService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {

    private final AuthService authService;

    private final UserRepository userRepository;

    public LoginController(AuthService authService, UserRepository userRepository) {
        this.authService = authService;
        this.userRepository = userRepository;
    }

    @GetMapping("/login")
    public String loginPage(@RequestParam(required = false) Boolean error, Model model) {
        if (Boolean.TRUE.equals(error)) {
            model.addAttribute("errorMessage", "用户名或密码错误");
        }
        return "login";
    }

    @PostMapping("/login")
    public String handleLogin(
            @RequestParam String username,
            @RequestParam String password,
            HttpServletRequest request,
            Model model) {

        if (authService.authenticate(username, password, request)) {
            // 创建会话
            HttpSession session = request.getSession();
            session.setAttribute("username", username);

            Users user = userRepository.findByUsername(username);
            if (user != null) {
                session.setAttribute("userId", user.getId());
                session.setAttribute("userEmail", user.getEmail());
            }

            session.setMaxInactiveInterval(30 * 60); // 30分钟会话超时

            return "redirect:/interview";
        } else {
            model.addAttribute("errorMessage", "用户名或密码错误");
            return "login";
        }
    }
}